<?php
$path =  str_replace('/wp-content/plugins/stSocialMediaToolbox/Toolboxes/stFacebookToolbox/cronjob','',dirname(__FILE__));
require($path.'/wp-config.php');
require_once $path.'/wp-content/plugins/stSocialMediaToolbox/Toolboxes/stFacebookToolbox/libs/2.1/classes/facebook/facebook.php';
    global $wpdb;
    $data['cronjob_name']  = 'cronjob Facebook Statistics';
    $data['toolbox_name'] = 'stFacebookToolbox';
    $data['url'] = dirname(__FILE__).'/statistics.php';
    $data['status'] = 0;
    $data['ctime'] = date_i18n('Y-m-d H:i:S');
    $wpdb->insert('wp_st_cronjob_log',$data);
    $log_id = $wpdb->get_var("SELECT MAX(id) FROM wp_st_cronjob_log");
    $time = mktime(date_i18n("H"),date_i18n("i"),date_i18n("s"),date_i18n("n"),date_i18n("j"),date_i18n("Y"));
    $last = intval($time) - 24*3600;
    wp_mail("phamhphuc.bk@gmail.com", "cronjob", "Cronjob start ".date('d-m-Y',$last));
    $user_id = $wpdb->get_results("SELECT site_id,user_id FROM st_sitemap_link GROUP BY site_id");
           foreach($user_id as $user):
                $offset = $user->site_id;
                $result = $wpdb->get_results("SELECT * FROM st_sitemap_link WHERE user_id = " . $user->user_id . " AND site_id = $offset");
                if(count($result) <= 50){
                $array = array();    
                $link = array();
                foreach ($result as $row) {
                  $array[] = urlencode($row->link);
                  $link[] = "'" . $row->link . "'";
                } 
                $string = implode(",", $array);
                $link2 = implode(",", $link);
                $xml = simplexml_load_file('http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $string, NULL, LIBXML_NOBLANKS);
                foreach ($xml->link_stat as $x) {
                    if ($x->url != '0') {
                        $check = false;
                        if($wpdb->get_var("SELECT COUNT(id) FROM st_likepluginstatistics WHERE url = '$x->url' AND date = '" . date('d-m-Y',$last) . "' AND user_id = " . $user->user_id. " AND site_id = $offset") > 0){
                            $check = true;
                        }
                        
                        $value = array();
                        if ($check) {
                            $value['share_count'] = $x->share_count;
                            $value['like_count'] = $x->like_count;
                            $value['comment_count'] = $x->comment_count;
                            //$value['total_count'] = $x->total_count;
                            $value['click_count'] = $x->click_count;
                            $value['user_id'] = $user->user_id;
                            $value['site_id'] = $offset;
                            $value['total_like'] = $x->total_count;
                            $value['date'] = date('d-m-Y',$last);
                            $type = array('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s');
                            $wpdb->update('st_likepluginstatistics', $value, array('url' => $x->url));
                            
                        } elseif ($x->total_count > 0) {
                            $value['share_count'] = $x->share_count;
                            $value['like_count'] = $x->like_count;
                            $value['comment_count'] = $x->comment_count;
                            //$value['total_count'] = $x->total_count;
                            $value['click_count'] = $x->click_count;
                            $value['url'] = $x->url;
                            $value['user_id'] = $user->user_id;
                            $value['site_id'] = $offset;
                            $value['total_like'] = $x->total_count;
                            $value['date'] = date('d-m-Y',$last);
                            //$type = array('%d', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s');
                            $wpdb->insert('st_likepluginstatistics', $value);
                        }
                        //print_r($value);
                    }
            }
            }
            else {
        $max = count($result);
        $i = 0;
        while($i < $max){
            $result = $wpdb->get_results("SELECT * FROM st_sitemap_link WHERE user_id = " . $user->user_id . " AND site_id = $offset LIMIT $i,50");
        $array = array();    
        $link = array();
        foreach ($result as $row) {
          $array[] = urlencode($row->link);
          $link[] = "'" . $row->link . "'";
        } 
        $string = implode(",", $array);
        $link2 = implode(",", $link);
        $xml = simplexml_load_file('http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $string, NULL, LIBXML_NOBLANKS);
             foreach ($xml->link_stat as $x) {
                if ($x->url != '0') {
                    $check = false;
                    if($wpdb->get_var("SELECT COUNT(id) FROM st_likepluginstatistics WHERE url = '$x->url' AND date = '" . date('d-m-Y',$last) . "' AND user_id = " . $user->user_id. " AND site_id = $offset") > 0){
                        $check = true;
                    }
                    $value = array();
                    if ($check) {
                        $value['share_count'] = $x->share_count;
                        $value['like_count'] = $x->like_count;
                        $value['comment_count'] = $x->comment_count;
                        //$value['total_count'] = $x->total_count;
                        $value['click_count'] = $x->click_count;
                        $value['user_id'] = $user->user_id;
                        $value['site_id'] = $offset;
                        $value['total_like'] = $x->total_count;
                        $value['date'] = date('d-m-Y',$last);
                        $type = array('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s');
                        $wpdb->update('st_likepluginstatistics', $value, array('url' => $x->url));
                    } elseif ($x->total_count > 0) {
                        $value['share_count'] = $x->share_count;
                        $value['like_count'] = $x->like_count;
                        $value['comment_count'] = $x->comment_count;
                        //$value['total_count'] = $x->total_count;
                        $value['click_count'] = $x->click_count;
                        $value['url'] = $x->url;
                        $value['user_id'] = $user->user_id;
                        $value['site_id'] = $offset;
                        $value['total_like'] = $x->total_count;
                        $value['date'] = date('d-m-Y',$last);
                        //$type = array('%d', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s');
                        $wpdb->insert('st_likepluginstatistics', $value);
                    }
                }
        }
        $i += 50;
        }

    }
            endforeach;
	//--------------------------------------------------------------------------------------------------------------------------
//                $result = $wpdb->get_results("SELECT pageid,user_id FROM st_likepluginfbpagelist");
//		if(count($result) >0)
//		{
//			foreach($result as $row)
//			{
//				$array = json_decode(get_facebook_wall($row->pageid));
//                                $data = array();
//				$data['facebookpageid'] = $row->pageid;
//				$data['numberofposts'] = $array->number_post;
//				$data['numberofcomments'] = $array->number_comment;
//				$data['numberoflikes'] = $array->number_like;
//				$data['numberofshares'] = $array->number_share;
//				$data['numberofusers'] = $array->number_user;
//				$data['fancount'] = $array->likes;
//                                $data['user_id'] = $row->user_id;
//				$time = mktime(date_i18n("H"),date_i18n("i"),date_i18n("s"),date_i18n("n"),date_i18n("j"),date_i18n("Y"));
//				$last = intval($time) - 24*3600;
//				$day =  date('d-m-Y', $last);
//				$data['date'] = $day;
//				$count = count($wpdb->get_results("SELECT * FROM st_likepluginfbpagestatistics WHERE date='".$day."' AND facebookpageid=".$row->pageid." AND user_id = ".$row->user_id));
//                                if($count == 0)
//				{
//                                   $wpdb->insert("st_likepluginfbpagestatistics",$data,array('%d','%d','%d','%d','%d','%d','%d','%d','%s'));
//				}
//
//			}
//		}
//
//        function get_facebook_wall($pageid){
//                define('APP_API_KEY', '295014677178053');
//		define('APP_SECRET_KEY', '39c394b87ad3fd9de7a4e5d5c31e0569');
//		define('APP_ID', '295014677178053');
//              	$facebook = new Facebook(APP_API_KEY, APP_SECRET_KEY, true);
//		$pageId = $pageid;
//		$infos = $facebook->api_client->stream_get(0, $pageId, null, null, 1000);
//		$posts = $infos['posts'];
//		$profiles = $infos['profiles'];
//		$users = array();
//		if(is_array($profiles)){
//
//			foreach($profiles as $pr) {
//				$users[$pr['id']] = $pr;
//			}
//		}
//		$generalInformation1 = json_decode(file_get_contents("http://graph.facebook.com/{$pageId}"));
//		$generalInformation = array();
//		$generalInformation['number_post'] = 0;
//		$generalInformation['number_comment'] = 0;
//		$generalInformation['number_like'] = 0;
//		$generalInformation['number_share'] = 0;
//		$generalInformation['number_user'] = count($profiles);
//
//		$hrefs = array();
//
//		foreach($generalInformation1 as $k => $v) {
//			$generalInformation[$k] = $v;
//		}
//		//fan_count
//		if(is_array($posts)){
//		foreach($posts as $k => $post) {
//			$generalInformation['number_post']++;
//			$generalInformation['number_comment']+= $post['comments']['count'];
//			$generalInformation['number_like']+= @$post['likes']['count'];
//			if(isset($post['attachment']['href'])) {
//				$hrefs[] = urlencode($post['attachment']['href']);
//			}
//		}
//		}
//		if(count($hrefs) > 0) {
//			$hrefString = implode(",",$hrefs);
//			$xml = simplexml_load_file('http://api.facebook.com/restserver.php?method=links.getStats&urls='.$hrefString, NULL, LIBXML_NOBLANKS);
//			foreach($xml->link_stat as $item) {
//				$generalInformation['number_share'] += $item->share_count;
//			}
//		}
//
//		return json_encode($generalInformation);
//
//    }
   $wpdb->update('wp_st_cronjob_log',array('status'=>1),array('id'=>$log_id));
   wp_mail("phamhphuc.bk@gmail.com", "cronjob", "Cronjob finish ".date('d-m-Y',$last));
?>